const util = require('../../common/util');
const config = require('../../common/config');
const sqlite3 = require('sqlite3');

class CartDB{
    /**
     * 构造函数
     * @param {String} dbFile 数据库文件路径
     * @constructor
     */
    constructor() {
        this.dbFile = config.dbFile;
        this.instance = null;
        this.db = null;
    }
    // 获取数据库实例
    /**
     * @returns {CartDB} CartDB实例
     */
    static getInstance() {
        if (!this.instance) {
            try {
                this.instance = new CartDB();
            } catch (err) {
                util.err(err);
            }
        }
        util.log("CartDB实例已创建");
        return this.instance;
    }

    /**
     * @returns {Promise} Promise对象
     */
    async connect() {
        if (this.isConnected) return; // 避免重复连接
        return new Promise((resolve, reject) => {
            this.db = new sqlite3.Database(this.dbFile, (err) => {
                if (err) {
                    util.err('数据库连接失败', err);
                    return reject(err);
                }
                this.isConnected = true;
                util.log('数据库连接成功');
                this.db.run(``, (err) => {
                    if (err) util.err('表结构初始化警告');
                    resolve();
                });
            });

            // ✅ 连接错误监听（持续重连逻辑）
            this.db.on('error', (err) => {
                util.err('数据库连接断开', err);
                this.isConnected = false;
                // 可选：5秒后自动重连
                setTimeout(() => this.connect(), 5000);
            });
        });
    }

    add(cart){
        return new Promise((resolve, reject) => {
            const sql = `
                INSERT INTO cart (
                    user_id , product_id , add_time ,  lastupdate_time ,quantity ,unit_price,money 
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
            `;
            const values=[
                cart.user_id ,
                cart.product_id ,
                new Date().toISOString(),
                new Date().toISOString(),
                cart.quantity ,
                cart.unit_price ,
                cart.money
            ];
            this.db.run(sql, values, function (err) {
                if (err) {
                    reject(err);
                } else {
                    util.log(`Inserted goods with id: ${this.lastID}`);
                    resolve(this.lastID); // 返回插入的goods_id
                }
            });
        });
    }


    update(cart) {
        return new Promise((resolve, reject) => {
            const sql = `
                UPDATE cart SET
                lastupdate_time =?, quantity =?, money =?
                WHERE user_id =? and product_id =?
            `;
            const params = [
                new Date().toISOString(),
                cart.quantity ,
                cart.money ,
                cart.user_id ,
                cart.product_id ,
            ];
            console.log('购物车更新',params);
            this.db.run(sql, params, function (err) {
                if (err) {
                    util.err('购物车更新失败', err); // 使用工具函数记录错误日志
                    return reject(err);
                }
            util.log(`购物车更新成功，受影响行数: ${this.changes}`); // 输出受影响行数
            resolve(this.changes);
            });
        });
    }
    
    //删除一条记录
    remove(user_id,product_id){
        const sql = `DELETE FROM cart WHERE user_id = ? and product_id = ?`;
        return new Promise((resolve, reject)=>{
            this.db.run(sql, [user_id, product_id] ,function (err){
                err ? reject(err) : resolve(this.changes);
            })
        })
    }

    //删除用户所有的购物车记录
    removeall(user_id){
        const sql = `DELETE FROM cart WHERE user_id = ? `;
        return new Promise((resolve, reject)=>{
            this.db.run(sql, user_id ,function (err){
                err ? reject(err) : resolve(this.changes);
            })
        })
    }

    findByuser_id(user_id){
        return new Promise((resolve, reject) => {
            const sql = "SELECT * FROM cart WHERE user_id = ? ";
            this.db.all(sql, user_id, (err, result) => {
                err ? reject(err) : resolve(result);
            });
        });
    }

    findByPrimaryKey(user_id,product_id){
        return new Promise((resolve, reject) => {
            const sql = "SELECT * FROM cart WHERE user_id = ? and product_id = ?";
            this.db.get(sql, [user_id,product_id], (err, result) => {
                err ? reject(err) : resolve(result);
            });
        });
    }
}

module.exports = CartDB;